﻿using Mozhi.Abp.Domain.BasicData;
using System;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace mozhi.smarterp.Business.Products
{
    public class ProductSaleSetting : AuditedAggregateRoot<Guid>, IMultiTenant
    {
        public Guid? TenantId { get; private set; }

        public Guid ProductId { get; private set; }

        public Product Product { get; private set; }

        public ProductAuxiliaryUnit AuxiliaryUnit { get; private set; }

        /// <summary>
        /// 销售单位
        /// </summary>
        public Guid? SaleUnitId { get; private set; }

        public Unit SaleUnit { get; private set; }


        private ProductSaleSetting() { }

        public ProductSaleSetting(Guid id, Product product, Unit saleUnit, ProductAuxiliaryUnit auxiliaryUnit)
        {
            Id = id;

            Change(product, saleUnit, auxiliaryUnit);
        }

        public void Change(Product product, Unit saleUnit , ProductAuxiliaryUnit auxiliaryUnit)
        {
            Product = product;
            AuxiliaryUnit = auxiliaryUnit;
            SaleUnit = saleUnit;

            ProductId = Product == null ? default : product.Id;
            SaleUnitId = SaleUnit == null ? default : saleUnit.Id;

            Validate();
        }

        #region
        private void Validate()
        {
            if (Product == null)
                throw new UserFriendlyException($"产品不存在", "100000");

            Product.Validate();

            if(SaleUnit==null)
                throw new UserFriendlyException($"销售单位不存在", "100000");
            SaleUnit.Validate();

            if(Product.BasicUnitId!=SaleUnitId && AuxiliaryUnit==null)
                throw new UserFriendlyException($"产品:{Product.Code}辅助单位：{SaleUnit.Name}换算关系不存在", "100000");

            if (AuxiliaryUnit != null)
                AuxiliaryUnit.Validate();

            Check.NotDefaultOrNull<Guid>(ProductId, nameof(ProductId));

            Check.NotDefaultOrNull<Guid>(SaleUnitId, nameof(SaleUnitId));   
        }
        #endregion
    }
}
